import { instantiate, Node, Prefab, Vec3 } from "cc";
import { ecsclass, ECSSystem } from "../../../app-core/ecs/ECSWorld";
import { MovableComponent } from "../components/MovableComponent";
import { NpcComponent } from "../components/NpcComponent";
import { NpcRenderComponent } from "../components/NpcRenderComponent";

const DIRECTIONS = ["up", "down", "left", "right"];
@ecsclass("NpcSystem")
export class NpcSystem extends ECSSystem {
    private createCountdown = 0;

    constructor(readonly renderNode: Node, readonly npcPrefab: Prefab) {
        super();
    }

    start(): void {
        super.start();

    }

    stop(): void {

        super.stop();
    }

    update(dt) {
        super.update(dt);

        this.createCountdown -= dt;
        if (this.createCountdown <= 0) {
            // 确定下一次创建 NPC 的倒计时
            this.createCountdown = 0.5;

            if (this.ecs.components.all(NpcComponent).length < 10) {
                // 当前存活的 NPC 少于 10 个时，创建新 NPC
                this.createNPC();
            }
        }
    }

    createNPC() {


        const npc = this.ecs.entities.add();
        console.log('NPCSystem create npc: ' + npc.id);

        npc.addComponent(new NpcComponent());

        let node = instantiate(this.npcPrefab);
        node.parent = this.renderNode;
        npc.addComponent(new NpcRenderComponent(instantiate(this.npcPrefab), this.renderNode));

        const direction = DIRECTIONS[Math.floor(Math.random() * DIRECTIONS.length)];
        const speed = Math.random() * 100 + 10;

        npc.addComponent(new MovableComponent(new Vec3(), direction, speed));
    }
}